package cn.sc.allinpay.allfavour.business.cashiertrsdetail;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.allinpay.usdk.core.data.ResponseData;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import cn.pai.common.listener.OnPromptListener;
import cn.pai.common.utils.AmtUtils;
import cn.pai.mvp.callback.MpCallBack;
import cn.pai.mvp.intervenor.Intervenor;
import cn.pai.mvp.presenter.PaiPresenter;
import cn.sc.allinpay.allfavour.app.Constant;
import cn.sc.allinpay.allfavour.base.db.DbDao;
import cn.sc.allinpay.allfavour.business.common.app.Global;
import cn.sc.allinpay.allfavour.business.common.data.CouponsData;
import cn.sc.allinpay.allfavour.business.common.data.OrderData;
import cn.sc.allinpay.allfavour.business.common.data.OrderPaymentInfo;
import cn.sc.allinpay.allfavour.business.common.data.PayInfo;
import cn.sc.allinpay.allfavour.business.common.data.PosData;
import cn.sc.allinpay.allfavour.business.common.data.SpOrderInfo;
import cn.sc.allinpay.allfavour.business.common.data.TransRecord;
import cn.sc.allinpay.allfavour.business.common.dialog.ManagerInputPwdDialog;
import cn.sc.allinpay.allfavour.business.common.utils.SpUtils;
import cn.sc.allinpay.allfavour.business.payment.PaymentActivity;
import cn.sc.allinpay.allfavour.module.allin.AllinUtils;
import cn.sc.allinpay.allfavour.module.device.DeviceLogin;
import cn.sc.allinpay.allfavour.module.printer.IPrinter;
import cn.sc.allinpay.allfavour.module.printer.PrintData;
import cn.sc.allinpay.allfavour.module.printer.PrintManager;

/**
 * 交易交易详情 presenter
 * author：pany
 * on 2017/12/1 11:27
 */
public class CashierTransDetailPresenter extends PaiPresenter<CashierTransDetailContract.View> implements CashierTransDetailContract.Presenter {

    public static final int REQ_PAYMENT = 0x01;//支付页面
    public static final int REQ_SALE_VOID = 0x02;//消费撤销
    public static final int REQ_PRINT_MERCHANT = 0x03;
    public static final int REQ_PRINT_CUSTOMER = 0x04;

    public static final int REQ_PRINT_MERCHANT_VOID= 0x05;
    public static final int REQ_PRINT_CUSTOMER_VOID = 0x06;

    private CashierTransDetailModel model = new CashierTransDetailModel();

    private TransRecord transRecord;//交易记录
    private OrderData payOrder;//支付订单数据
    private PosData posData;//pos数据
    private SpOrderInfo spOrderInfo;
    private IPrinter printer;
    private boolean isProcesing;

    private boolean isRecordChange = false;//交易记录是否修改

    @Override
    protected Intervenor createIntervenor() {
        return new Intervenor() {
            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                Bundle bundle = view.getBundle();
                transRecord = bundle.getParcelable(Constant.BundleKey.TRANS_RECORD);
            }

            @Override
            public void onResume() {
                super.onResume();
                DeviceLogin.login(view.getContext());
            }

            @Override
            public void onPause() {
                super.onPause();
                DeviceLogin.logout();
            }

//            @Override
//            public void onActivityResult(int requestCode, int resultCode, Intent data) {
//                super.onActivityResult(requestCode, resultCode, data);
//                if (Activity.RESULT_OK == resultCode) {
//                    if (REQ_SALE_VOID == requestCode || REQ_SCAN_VOID == requestCode) {//刷卡消费成功
//                        if (data != null) {
//
//                        } else {
//                            view.toast("交易数据返回为空");
//                        }
//                    } else if (REQ_PAYMENT == requestCode) {//支付成功返回
//                        isRecordChange = true;
//                        DbDao<TransRecord> dbDao = model.getDao(TransRecord.class);
//                        transRecord = dbDao.query(transRecord.getId());
//                        payOrder = JSON.parseObject(transRecord.getOrderData(), OrderData.class);
//                        if (!TextUtils.isEmpty(transRecord.getPosData())) {
//                            posData = JSON.parseObject(transRecord.getPosData(), PosData.class);
//                        }
//                        refreshState();
//                    } else if (REQ_PRINT == requestCode) {
//
//                    }
//
//                } else {
//                    if (data != null) {
//                        String reson = data.getStringExtra("reason");
//                        if (!TextUtils.isEmpty(reson)) {
//                            view.toast(reson);
//                        } else {
//                            view.toast("交易失败");
//                        }
//                    }
//                }
//            }

            @Override
            public void onActivityResult(int requestCode, int resultCode, Intent data) {
                super.onActivityResult(requestCode, resultCode, data);
                if (data != null && data.getExtras() != null) {
                    Bundle extras = data.getExtras();
                    ResponseData result = (ResponseData) extras.getSerializable("RESPONSE");
                    if (result != null) {
                        if (result.getValue("REJCODE").equals("00")) {
                            if (REQ_SALE_VOID == requestCode) {//刷卡撤销成功
                                posData.setTraceNo(result.getValue("TRACE_NO"));//凭证号
                                posData.setBatchNo(result.getValue("BATCH_NO"));//批次号
                                posData.setReferenceNo(result.getValue("REF_NO"));//参考号
                                String dateTime = AllinUtils.getSysYear() + result.getValue("DATE") + result.getValue("TIME");
                                posData.setDateTime(dateTime);//交易时间 格式yyyyMMddHHmmss
                                posData.setTransactionNumber(result.getValue("TRANS_TICKET_NO"));//交易单号
                                isRecordChange = true;
                                transRecord.setState(4);//撤销成功
                                DbDao<TransRecord> dbDao = model.getDao(TransRecord.class);
                                dbDao.update(transRecord);
                                refreshState();
                                Date myDate1 = new Date();
                                DateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                view.loading();
                                model.payNotify(transRecord.getOrderId(), "bank", "CANCEL", dateFormat2.format(myDate1), "0", "0", posData.getTransactionNumber(), new MpCallBack<JSONObject, String>() {
                                    @Override
                                    public void onSuccess(JSONObject resp) {
                                        view.loaded();
                                        view.toast("撤销成功");
                                        print();
                                        model.getGlobal().setPayInfo(null);
                                        SpUtils.put(view.getContext(), Constant.SPNAME, Constant.SpKey.PayInfo, JSON.toJSONString(""));
                                    }
                                    @Override
                                    public void onFailure(String resp, String message) {
                                        view.loaded();
                                        view.prompt(message);
                                    }
                                });
                            } else if (REQ_PRINT_MERCHANT == requestCode) {
                                AllinUtils.printOrder(spOrderInfo, false,false, view.getActivity(), REQ_PRINT_CUSTOMER);
                            } else if (REQ_PRINT_CUSTOMER == requestCode) {
                                print();
                            } else if (REQ_PRINT_MERCHANT_VOID == requestCode) {
                                AllinUtils.printOrder(spOrderInfo, false,true, view.getActivity(), REQ_PRINT_CUSTOMER_VOID);
                            } else if (REQ_PRINT_CUSTOMER_VOID == requestCode) {
                                print();
                            }
                        } else {
                            String error = result.getValue("REJCODE_CN");
                            view.toast(error);

                            if (REQ_SALE_VOID == requestCode) {
                                model.getGlobal().setPayInfo(null);
                                SpUtils.put(view.getContext(), Constant.SPNAME, Constant.SpKey.PayInfo, JSON.toJSONString(""));
                            }
                        }
                    }
                }
            }
        };
    }

    @Override
    public void start() {
        if (initData()) {
            initView();
        } else {
            view.toast("初始化数据失败");
            view.finish();
        }
    }

    /**
     * 数据初始化
     *
     * @return
     */
    private boolean initData() {
        if (transRecord == null) {
            view.toast("交易记录不能为空");
            view.finish();
            return false;
        }
        if (TextUtils.isEmpty(transRecord.getOrderData())) {
            view.toast("订单数据不能为空");
            view.finish();
            return false;
        }
        payOrder = JSON.parseObject(transRecord.getOrderData(), OrderData.class);
        if (!TextUtils.isEmpty(transRecord.getPosData())) {
            posData = JSON.parseObject(transRecord.getPosData(), PosData.class);
        }
        return true;
    }

    /**
     * 初始化视图
     */
    private void initView() {
        view.showOrderId(payOrder.getOrderId());//订单号
        view.showTransTime(transRecord.getTransDate() + transRecord.getTransTime());//交易时间
        if (model.getGlobal().getCashierData() != null) {
            view.showCashierName(model.getGlobal().getCashierData().getCashierName());//收银员
        }
        view.showGuideName("");//导购员
        view.showTransAmt(AmtUtils.formatY(payOrder.getTransAmt()));//交易金额

        view.showMemberNo(payOrder.getMemberData() != null ? payOrder.getMemberData().getCardNo() : "无");
        view.showDiscount(payOrder.getMemberData() != null ? payOrder.getMemberData().getOilDiscountAmt().toString(): "0.00");
        view.showCoupons(!TextUtils.isEmpty(payOrder.getDisCouponAmt()) ? AmtUtils.formatY(payOrder.getDisCouponAmt()) : "0.00");
        if (!TextUtils.isEmpty(payOrder.getDisCouponAmt()) && payOrder.getMemberData() != null) {
            List<CouponsData> couponsList = payOrder.getMemberData().getCoupons();
            if (couponsList != null && !couponsList.isEmpty()) {
                for (int i = 0; i < couponsList.size(); i++) {
                    CouponsData couponsData = couponsList.get(i);
                    if (couponsData.getUseNumber() == 0 && (couponsData.getUseAmt() == null || TextUtils.isEmpty(couponsData.getUseAmt()) || BigDecimal.ZERO.compareTo(new BigDecimal(couponsData.getUseAmt())) == 0)) {
                    } else {
                        if (couponsData.isUse()) {
                            if (couponsData.getType() == 0) {//金额
                                view.addCouponView(couponsData.getCouponName(), couponsData.getUseAmt());
                            } else {
                                view.addCouponView(couponsData.getCouponName(), couponsData.getUseNumber() + couponsData.getUnit());
                            }
                        }
                    }

                }
            }
        }
        view.showEWalletAmt(!TextUtils.isEmpty(payOrder.getDisEWalletAmt()) ? AmtUtils.formatY(payOrder.getDisEWalletAmt()) : "0.00");

        refreshOrder();
    }

    public void refreshOrder() {
        if (transRecord == null || TextUtils.isEmpty(transRecord.getOrderData())) {
            refreshState();
            return;
        }
        if (payOrder.getSpOrderCode() == null || transRecord.getState() != 1) {
            refreshState();
            return;
        }
        view.loading("订单查询中...");
        view.showBtnPrint(View.GONE);
        view.showBtnPosPay(View.GONE);
        view.showBtnPosVoid(View.GONE);
        view.showBtnDisVoid(View.GONE);
        model.spOrderInfo(payOrder.getOrderId(), new MpCallBack<SpOrderInfo, String>() {
            @Override
            public void onSuccess(SpOrderInfo orderInfo) {
                view.loaded();
                if (orderInfo.getOrderPayment() != null && orderInfo.getOrderPayment().size() != 0) {
                    OrderPaymentInfo orderPaymentInfo = orderInfo.getOrderPayment().get(0);
                    int paymentFrom = orderPaymentInfo.getPaymentFrom();
                    String payFrom = "扫码支付";
                    if (paymentFrom == 0) {
                        payFrom = "微信支付";
                    } else if (paymentFrom == 1) {
                        payFrom = "支付宝支付";
                    } else if (paymentFrom == 2) {
                        payFrom = "手机 QQ 支付";
                    } else if (paymentFrom == 3) {
                        payFrom = "银联支付";
                    }
                    posData.setTransType(payFrom);//交易类型
                    posData.setBatchNo(orderPaymentInfo.getTrxId());//批次号

                    String dateTime = orderInfo.getCreateTime();
                    Date myDate1 = new Date();
                    DateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    try {
                        myDate1 = dateFormat1.parse(dateTime);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    DateFormat dateFormat2 = new SimpleDateFormat("yyyyMMddHHmmss");
                    posData.setDateTime(dateFormat2.format(myDate1));//交易时间 格式yyyyMMddHHmmss

                    if (orderInfo.getRmaId() == null || (orderInfo.getRmaId() != null && orderInfo.getRefundStatus() == 3)) {
                        if (orderInfo.getOrderStatus() == 0) {

                            updRecord(0);

                        } else if (orderInfo.getOrderStatus() == 1) {

                            updRecord(2);

                            spOrderInfo = orderInfo;
                            if (orderInfo.getOrderPayment() != null && orderInfo.getOrderPayment().size() != 0) {
                                model.payNotify(payOrder.getOrderId(), "scan", "PAY", orderPaymentInfo.getPaymentTime(), AmtUtils.changeY2F(posData.getCashAmt()), AmtUtils.changeY2F(orderPaymentInfo.getPaymentAmount()), null, new MpCallBack<JSONObject, String>() {
                                    @Override
                                    public void onSuccess(JSONObject resp) {
                                        view.loaded();
                                        AllinUtils.printOrder(spOrderInfo, true,false, view.getActivity(), REQ_PRINT_MERCHANT);
                                    }
                                    @Override
                                    public void onFailure(String resp, String message) {
                                        view.loaded();
                                        view.prompt(message);
                                    }
                                });
                            }
                        } else if (orderInfo.getOrderStatus() == 2) {

                            updRecord(0);

                        } else if (orderInfo.getOrderStatus() == 3) {


                            updRecord(4);

                        } else if (orderInfo.getOrderStatus() == 4) {
                            isProcesing = true;
                            updRecord(1);

                        }
                    } else if (orderInfo.getRmaId() != null && orderInfo.getRefundStatus() != 3) {
                        if (orderInfo.getRefundStatus() == 1) {

                            updRecord(3);
                        } else if (orderInfo.getRefundStatus() == 2) {

                            updRecord(4);
                        }
                    }
                } else {
                    posData = null;
                    updRecord(0);
                }
                refreshState();
            }

            @Override
            public void onFailure(String resp, String message) {
                view.loaded();
                view.prompt(message);
            }
        });
    }

    /**
     * 修改交易记录
     *
     * @param state 支付状态  1:支付中 2:支付成功(全单支付完成) 3:撤销中(尚有其他子订单尚未撤销成功的) 4:撤销成功(全单撤销完成)
     * @return
     */
    private int updRecord(int state) {
        transRecord.setPosData(JSON.toJSONString(posData));
        transRecord.setState(state);
        transRecord.setOrderData(JSON.toJSONString(payOrder));
        return model.updTransRecord(transRecord);
    }

    /**
     * SellState：抵扣状态  0:无抵扣(普通交易) 1:部分抵扣成功  2:抵扣撤销 3:全额抵扣成功 4：全额抵扣撤销
     * state：支付状态   1:支付中 2:支付成功(全单支付完成) 3:撤销中(尚有其他子订单尚未撤销成功的) 4:撤销成功(全单撤销完成
     */
    private void refreshState() {
        if (transRecord.getSellState() == 0) {
            view.showDisState("无抵扣");
            view.showBtnDisVoid(View.GONE);
        } else if (transRecord.getSellState() == 1) {
            view.showDisState("部分抵扣");
            view.showBtnDisVoid(View.VISIBLE);
        } else if (transRecord.getSellState() == 2) {
            view.showDisState("部分抵扣撤销");
            view.showBtnDisVoid(View.GONE);
        } else if (transRecord.getSellState() == 3) {
            view.showDisState("全额抵扣");
            view.showBtnDisVoid(View.VISIBLE);
        } else if (transRecord.getSellState() == 4) {
            view.showDisState("全额抵扣撤销");
            view.showBtnDisVoid(View.GONE);
        }

        if (transRecord.getState() == 0) {
            view.showPosState("待支付");
            view.showBtnPosVoid(View.GONE);
            view.showBtnPosPay(View.VISIBLE);
            view.showPosAmt("支付金额:      " + AmtUtils.formatY(payOrder.getPaidAmt()));
        } else if (transRecord.getState() == 1) {
            view.showPosState("支付中");
            view.showBtnPosVoid(View.VISIBLE);
            view.showBtnPosPay(View.VISIBLE);
            view.showBtnPrint(View.GONE);
            view.showPosAmt("支付金额:      " + AmtUtils.formatY(payOrder.getPaidAmt()));
            if (isProcesing) {
                view.showBtnPosVoid(View.GONE);
                view.showBtnPosPay(View.GONE);
            }
        } else if (transRecord.getState() == 2) {
            view.showPosState("支付成功");
            view.showBtnPosVoid(View.VISIBLE);
            view.showBtnPosPay(View.GONE);
        } else if (transRecord.getState() == 3) {
            view.showPosState("撤销中");
            view.showBtnPosVoid(View.VISIBLE);
            view.showBtnPosPay(View.GONE);
        } else if (transRecord.getState() == 4) {
            view.showPosState("撤销成功");
            view.showBtnPosVoid(View.GONE);
            view.showBtnPosPay(View.GONE);
        }

        if (posData != null) {
            view.showBtnPrint(View.VISIBLE);
            if ("现金支付".equals(posData.getTransType())) {
                view.showPosAmt(posData.getTransType() + ":      " + posData.getCashAmt());
            } else {
                view.showPosAmt(posData.getTransType() + ":      " + AmtUtils.changeF2Y(posData.getAmount()));
                view.showCashAmt(!TextUtils.isEmpty(posData.getCashAmt()) ? "现金支付:      " + posData.getCashAmt() : null);
            }
            if (transRecord.getState() == 4) {
                view.showBtnPrint(View.GONE);
            }

            if (transRecord.getState() == 1) {
                view.showBtnPrint(View.GONE);
            }
        } else {
            if (transRecord.getSellState() == 3) {//全额抵扣
                view.showBtnPrint(View.VISIBLE);//可重打
                view.showPosView(View.GONE);
            } else if (transRecord.getSellState() == 4) {//全额抵扣撤销
                view.showBtnPrint(View.GONE);
                view.showPosView(View.GONE);
            } else {
                view.showBtnPrint(View.GONE);
                view.showPosView(View.VISIBLE);
            }
        }
    }

    @Override
    public void callPrint() {
        if (posData != null) {
//            AllinUtils.callPrint(view.getActivity(), posData.getTraceNo(), REQ_PRINT);
            print();
        } else {
            if (transRecord.getSellState() == 3) {
                printFull();
            }
        }
    }

    /**
     * 全卡券支付打印
     */
    public void printFull() {
        //因为onActivityResult回来没有立即执行onResume方法
        DeviceLogin.login(view.getContext());
        view.loading("正在打印...");
        PrintData data = new PrintData();
        data.setMerchantName(model.getGlobal().getConfigData().getMerName());
        data.setTerminalId(model.getGlobal().getConfigData().getTerId());
        data.setOperNo(payOrder.getCashierNo());
        data.setOilName(payOrder.getOilName());
        data.setOperName(payOrder.getCashierName());
        data.setOrderId(payOrder.getOrderId());//订单号
        data.setAmt(payOrder.getTransAmt());//订单总金额
        data.setCardNo(payOrder.getMemberData() != null ? payOrder.getMemberData().getCardNo() : null);//会员卡号
        data.setDisRightsAmt(payOrder.getMemberData() != null ? payOrder.getMemberData().getOilDiscountAmt().toString() : null);//会员权益优惠
        data.setDisCouponAmt(payOrder.getDisCouponAmt());//卡券使用金额
        data.setDisEWalletAmt(payOrder.getDisEWalletAmt());//电子钱包使用金额
        data.setTime(transRecord.getTransDate() + transRecord.getTransTime());//交易时间
        data.setTransDate(transRecord.getTransDate());
        data.setTransTime(transRecord.getTransTime());
        data.setCouponUrl(model.getGlobal().getCashierData().getUrlPrefix());
        data.setPrintCount(payOrder.getPrintCount());
        printer = PrintManager.createPrinter(PrintManager.PRINT_CASHIER_FULL, data);
        printer.print(new IPrinter.OnPrintListener() {
            @Override
            public void onStart(int step) {

            }

            @Override
            public void onSuccess(int step) {
                view.loaded();
                view.toast("打印成功");
               String printCount = payOrder.getPrintCount();
               if (printCount == null) {
                   payOrder.setPrintCount("1");
               } else {
                   printCount = Integer.parseInt(printCount) + 1 + "";
                   payOrder.setPrintCount(printCount);
               }

                transRecord.setOrderData(JSON.toJSONString(payOrder));
                model.updTransRecord(transRecord);

            }

            @Override
            public void onFail(int code, String msg) {
                view.loaded();
                view.prompt(false, msg + ",是否继续打印", new OnPromptListener("确定", "取消") {
                    @Override
                    public void onPositive(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        print();
                    }

                    @Override
                    public void onNegative(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        view.setResult(Activity.RESULT_OK, null);
                        view.finish();
                    }
                });
            }
        });
    }

    /**
     * 打印支付摘要
     */
    public void print() {
        //因为onActivityResult回来没有立即执行onResume方法
        DeviceLogin.login(view.getContext());
        view.loading("正在打印...");
        PrintData data = new PrintData();
        data.setMerchantName(model.getGlobal().getConfigData().getMerName());
        data.setTerminalId(model.getGlobal().getConfigData().getTerId());
        data.setOperNo(payOrder.getCashierNo());
        data.setOperName(payOrder.getCashierName());
        data.setOilName(payOrder.getOilName());
        data.setOrderId(payOrder.getOrderId());//订单号
        data.setAmt(payOrder.getTransAmt());//订单总金额
        data.setCardNo(payOrder.getMemberData() != null ? payOrder.getMemberData().getCardNo() : null);//会员卡号
        data.setDisRightsAmt(payOrder.getMemberData() != null ? payOrder.getMemberData().getOilDiscountAmt().toString(): null);//会员权益优惠
        data.setDisCouponAmt(payOrder.getDisCouponAmt());//卡券使用金额
        data.setDisEWalletAmt(payOrder.getDisEWalletAmt());//电子钱包使用金额
        data.setTime(posData.getDateTime());//交易时间
        data.setCashAmt(posData.getCashAmt());//现金交易金额
        data.setTrsAmt(posData.getAmount());//非现金交易金额
        data.setCouponUrl(model.getGlobal().getCashierData().getUrlPrefix());
        data.setPrintCount(payOrder.getPrintCount());

        printer = PrintManager.createPrinter(PrintManager.PRINT_CASHIER, data);
        printer.print(new IPrinter.OnPrintListener() {
            @Override
            public void onStart(int step) {

            }

            @Override
            public void onSuccess(int step) {

                String printCount = payOrder.getPrintCount();
                if (printCount == null) {
                    payOrder.setPrintCount("1");
                } else {
                    printCount = Integer.parseInt(printCount) + 1 + "";
                    payOrder.setPrintCount(printCount);
                }

                transRecord.setOrderData(JSON.toJSONString(payOrder));
                model.updTransRecord(transRecord);

                view.loaded();
                view.toast("打印成功");
            }

            @Override
            public void onFail(int code, String msg) {
                view.loaded();
                view.prompt(false, msg + ",是否继续打印", new OnPromptListener("确定", "取消") {
                    @Override
                    public void onPositive(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        print();
                    }

                    @Override
                    public void onNegative(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        view.setResult(Activity.RESULT_OK, null);
                        view.finish();
                    }
                });
            }
        });
    }

    @Override
    public void reqVoidIntegral() {
        view.showManagerPwdDialog(new ManagerInputPwdDialog.OnDialogListener() {
            @Override
            protected void onConfirm(String input) {
                view.loading("积分撤销中...");
                model.reqVoidIntegral(transRecord.getOrderId(), new MpCallBack<JSONObject, String>() {
                    @Override
                    public void onSuccess(JSONObject resp) {
                        view.loaded();
                        reqVoidOrder();
                    }

                    @Override
                    public void onFailure(String response, String message) {
                        view.loaded();
                        view.prompt(message);
                    }
                });
            }
        });
    }

    @Override
    public void reqVoidOrder() {
        view.loading("抵扣撤销中...");
        model.reqVoidOrder(transRecord.getOrderId(), new MpCallBack<JSONObject, String>() {
            @Override
            public void onSuccess(JSONObject resp) {
                view.loaded();
                isRecordChange = true;
                /**
                 * SellState：抵扣状态  0:无抵扣(普通交易) 1:部分抵扣成功  2:抵扣撤销 3:全额抵扣成功 4：全额抵扣撤销
                 * state：支付状态   1:支付中 2:支付成功(全单支付完成) 3:撤销中(尚有其他子订单尚未撤销成功的) 4:撤销成功(全单撤销完成
                 */
                if (transRecord.getSellState() == 3) {//全额抵扣
                    transRecord.setSellState(4);//全额抵扣撤销
                } else {
                    transRecord.setSellState(2);//部分抵扣撤销
                    if (transRecord.getState() == 1) {//如果是支付中
                        transRecord.setState(4);//撤销成功
                    } else if (transRecord.getState() == 2) {//如果是支付成功
                        transRecord.setState(3);//撤销中
                        if (posData != null && "现金支付".equals(posData.getTransType())) {
                            transRecord.setState(4);//撤销成功
                        }
                    }
                }
                DbDao<TransRecord> dbDao = model.getDao(TransRecord.class);
                dbDao.update(transRecord);
                refreshState();
            }

            @Override
            public void onFailure(String response, String message) {
                view.loaded();
                view.prompt(message);
            }
        });
    }

    @Override
    public void callPosVoid() {
        if (transRecord.getSellState() == 1) {
            view.prompt("请先撤销抵扣金额");
            return;
        }
        view.showManagerPwdDialog(new ManagerInputPwdDialog.OnDialogListener() {
            @Override
            protected void onConfirm(String input) {
                PosData posData = JSON.parseObject(transRecord.getPosData(), PosData.class);
                if ("消费".equals(posData.getTransType())) {
                    PayInfo payInfo = new PayInfo();
                    payInfo.setAmount(posData.getAmount());
                    payInfo.setOrderId(posData.getOrderId());
                    payInfo.setType("cancel");
                    String transRecordJSON = JSON.toJSONString(transRecord);
                    payInfo.setTransRecordJSON(transRecordJSON);
                    String posDataJson = JSON.toJSONString(posData);
                    payInfo.setPosDataJSON(posDataJson);
                    model.getGlobal().setPayInfo(payInfo);
                    SpUtils.put(view.getContext(), Constant.SPNAME, Constant.SpKey.PayInfo, JSON.toJSONString(payInfo));
                    AllinUtils.callSaleVoid(view.getActivity(), posData.getAmount(), posData.getTraceNo(), posData.getOrderId(), REQ_SALE_VOID);
                } else if ("现金支付".equals(posData.getTransType())) {
                    isRecordChange = true;
                    transRecord.setState(4);//撤销成功
                    DbDao<TransRecord> dbDao = model.getDao(TransRecord.class);
                    dbDao.update(transRecord);
                    refreshState();
                    Date myDate1 = new Date();
                    DateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                    view.loading();
                    model.payNotify(transRecord.getOrderId(), "cash", "CANCEL", dateFormat2.format(myDate1), "0", "0", null, new MpCallBack<JSONObject, String>() {
                        @Override
                        public void onSuccess(JSONObject resp) {
                            view.loaded();
                            view.toast("撤销成功");
                            print();
                        }
                        @Override
                        public void onFailure(String resp, String message) {
                            view.loaded();
                            view.prompt(message);
                        }
                    });
                } else {
                    Global global = Global.getInstance();
                    String localServer = global.getServer();
                    if (localServer.equals("backup")) {
                        view.toast("“极速收银”模式下，不支持此操作");
                        return;
                    }

                    view.loading("订单撤销中...");
                    model.spCancelOrder(payOrder.getSpOrderCode(), new MpCallBack<JSONObject, String>() {
                        @Override
                        public void onSuccess(JSONObject orderInfo) {
                            isRecordChange = true;
                            transRecord.setState(4);//撤销成功
                            DbDao<TransRecord> dbDao = model.getDao(TransRecord.class);
                            dbDao.update(transRecord);
                            refreshState();
                            Date myDate1 = new Date();
                            DateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                            view.loading();
                            model.payNotify(transRecord.getOrderId(), "scan", "CANCEL", dateFormat2.format(myDate1), "0", "0", null, new MpCallBack<JSONObject, String>() {
                                @Override
                                public void onSuccess(JSONObject resp) {
                                    view.loaded();
                                    view.toast("撤销成功");
                                    view.loading("订单查询中...");
                                    view.showBtnPrint(View.GONE);
                                    view.showBtnPosPay(View.GONE);
                                    view.showBtnPosVoid(View.GONE);
                                    view.showBtnDisVoid(View.GONE);
                                    model.spOrderInfo(transRecord.getOrderId(), new MpCallBack<SpOrderInfo, String>() {
                                        @Override
                                        public void onSuccess(SpOrderInfo orderInfo) {
                                            view.loaded();
                                            spOrderInfo = orderInfo;
                                            AllinUtils.printOrder(spOrderInfo, true,true, view.getActivity(), REQ_PRINT_MERCHANT_VOID);
                                        }

                                        @Override
                                        public void onFailure(String resp, String message) {
                                            view.loaded();
                                            view.prompt(message);
                                        }
                                    });
                                }
                                @Override
                                public void onFailure(String resp, String message) {
                                    view.loaded();
                                    view.prompt(message);
                                }
                            });
                        }

                        @Override
                        public void onFailure(String response, String message) {
                            view.loaded();
                            view.prompt(message);
                        }
                    });

                }
            }
        });
    }

    @Override
    public void startPaymentActivity() {
        DateFormat dateFormat1 = new SimpleDateFormat("yyyyMMddHHmmss");
        try {
           Date myDate1 = dateFormat1.parse(transRecord.getTransDate() + transRecord.getTransTime());
           Date myDate2 = new Date();

            long between = (myDate2.getTime() - myDate1.getTime())/1000;
            long time = between/60;

            if (time > 10) {
                view.prompt("订单已超过10分钟，不能继续支付");
                return;
            }

            Bundle bundle = new Bundle();
            bundle.putParcelable(Constant.BundleKey.TRANS_RECORD, transRecord);
            view.toActivityForResult(PaymentActivity.class, bundle, REQ_PAYMENT);

        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void setActivityForResult() {
        if (isRecordChange) {
            view.setResult(Activity.RESULT_OK, null);
            view.finish();
        } else {
            view.finish();
        }
    }
}
